package ca.cbc.panacea.elixir.persistence;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public enum EntityFacade {
    instance;
   final Logger logger = LoggerFactory.getLogger(EntityManagerFactory.class);

   private EntityManagerFactory emf;

   private ThreadLocal<EntityManager> threadLocalEntityManager = new ThreadLocal<EntityManager>();

   private EntityFacade(){
      emf = Persistence.createEntityManagerFactory("persistenceUnit");
   }


   public EntityManager get() {

      logger.debug("Getting the current managed manager");
      EntityManager entityManager = threadLocalEntityManager.get();
      if (entityManager == null ) {
          entityManager = emf.createEntityManager();
          threadLocalEntityManager.set(entityManager);
      }
      return entityManager;
   }

   public void beginTransaction(){
       EntityManager em = get();
       if(!em.getTransaction().isActive()){
        em.getTransaction().begin();
       }
   }

    public void commitTransaction(){
        EntityManager em = get();
        em.getTransaction().commit();
    }

    public void rollbackTransaction() {
        EntityManager em = get();
        if(!em.getTransaction().isActive()){
         em.getTransaction().begin();
        }
    }
}
   
